package com.zf.zfed.audit.ui

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.zf.zfed.audit.R

/**
 * 带下拉选择的设置项控件
 */
@SuppressLint("ResourceAsColor", "RtlHardcoded")
class DropdownSetItem @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    
    // 图标
    private var itemIcon: ImageView
    
    // 名称
    private var itemName: TextView
    
    // 右侧文字
    private var rightText: TextView
    
    // 下拉箭头
    private lateinit var dropdownArrow: ImageView
    
    // 下拉菜单
    private var popupWindow: PopupWindow? = null
    
    // 选项列表
    private var options: List<String> = emptyList()
    
    // 当前选中的选项
    private var selectedOption: String = ""
    
    // 选项变化监听器
    private var onOptionChangeListener: ((String) -> Unit)? = null

    init {
        isClickable = true
        isFocusable = true
        orientation = VERTICAL
        
        // 设置卡片背景
        background = ContextCompat.getDrawable(context, R.drawable.card_background)
        
        // 设置卡片边距
        val cardPadding = context.dpFromDimen(R.dimen.spacing_5)
        setPadding(cardPadding, cardPadding, cardPadding, cardPadding)

        // 内嵌布局
        val nestedFrameLayout = FrameLayout(context)
        val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F)
        addView(nestedFrameLayout, layoutParams)

        // 图标
        itemIcon = ImageView(context)
        val iconSize = context.dpFromDimen(R.dimen.size_22)
        val iconLP = FrameLayout.LayoutParams(iconSize, iconSize)
        iconLP.gravity = Gravity.START or Gravity.CENTER_VERTICAL
        iconLP.leftMargin = context.dpFromDimen(R.dimen.spacing_16)
        itemIcon.scaleType = ImageView.ScaleType.CENTER_INSIDE
        nestedFrameLayout.addView(itemIcon, iconLP)

        // 文案
        itemName = TextView(context)
        itemName.setTextColor(ContextCompat.getColor(context, R.color.text_primary))
        itemName.textSize = context.spFromDimen(R.dimen.font_20)
        itemName.setTypeface(null, android.graphics.Typeface.BOLD)
        val textLP = FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        textLP.gravity = Gravity.START or Gravity.CENTER_VERTICAL
        textLP.leftMargin = context.dpFromDimen(R.dimen.spacing_50)
        nestedFrameLayout.addView(itemName, textLP)

        // 右侧文字
        rightText = TextView(context)
        rightText.setTextColor(ContextCompat.getColor(context, R.color.text_primary))
        rightText.textSize = context.spFromDimen(R.dimen.font_14)
        rightText.isClickable = true
        rightText.isFocusable = true
        val rightTextLP = FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        rightTextLP.gravity = Gravity.END or Gravity.CENTER_VERTICAL
        rightTextLP.marginEnd = context.dpFromDimen(R.dimen.spacing_16) // 右侧边距
        nestedFrameLayout.addView(rightText, rightTextLP)
        
        // 设置右侧文字点击监听器
        rightText.setOnClickListener {
            showDropdown()
        }

        // 下拉箭头 - 已移除
        // dropdownArrow = ImageView(context)
        // val arrowSize = context.dpFromDimen(R.dimen.size_16)
        // val arrowLP = FrameLayout.LayoutParams(arrowSize, arrowSize)
        // arrowLP.gravity = Gravity.END or Gravity.CENTER_VERTICAL
        // arrowLP.marginEnd = context.dpFromDimen(R.dimen.spacing_16)
        // dropdownArrow.setImageResource(R.drawable.arrow)
        // dropdownArrow.setColorFilter(ContextCompat.getColor(context, R.color.text_primary))
        // nestedFrameLayout.addView(dropdownArrow, arrowLP)

        // 设置点击监听器
        setOnClickListener {
            showDropdown()
        }

        if (attrs != null) {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.DropdownSetItem)
            val title = typedArray.getString(R.styleable.DropdownSetItem_dropdown_title)
            val iconRes = typedArray.getResourceId(R.styleable.DropdownSetItem_dropdown_icon, 0)
            val initialValue = typedArray.getString(R.styleable.DropdownSetItem_dropdown_initial_value)
            
            itemName.text = title
            rightText.text = initialValue ?: ""
            selectedOption = initialValue ?: ""
            
            if (iconRes != 0) {
                itemIcon.setImageResource(iconRes)
                itemIcon.visibility = VISIBLE
                itemIcon.setColorFilter(ContextCompat.getColor(context, R.color.text_primary))
            } else {
                itemIcon.visibility = GONE
            }
            
            typedArray.recycle()
        } else {
            itemIcon.visibility = GONE
        }
    }

    /**
     * 设置选项列表
     */
    fun setOptions(options: List<String>) {
        this.options = options
    }

    /**
     * 设置当前选中的选项
     */
    fun setSelectedOption(option: String) {
        selectedOption = option
        rightText.text = option
    }

    /**
     * 获取当前选中的选项
     */
    fun getSelectedOption(): String = selectedOption

    /**
     * 设置选项变化监听器
     */
    fun setOnOptionChangeListener(listener: (String) -> Unit) {
        onOptionChangeListener = listener
    }

    /**
     * 显示下拉菜单
     */
    private fun showDropdown() {
        if (options.isEmpty()) return

        val dropdownView = createDropdownView()
        
        // 计算下拉菜单宽度 - 只占用右侧小部分区域
        val maxTextWidth = calculateMaxTextWidth()
        val minWidth = context.dpFromDimen(R.dimen.size_160) // 最小宽度
        val maxWidth = width * 3 / 4 // 最大不超过卡片宽度的3/4
        val dropdownWidth = (maxTextWidth + context.dpFromDimen(R.dimen.spacing_22)).coerceIn(minWidth, maxWidth)
        
        popupWindow = PopupWindow(
            dropdownView,
            dropdownWidth,
            FrameLayout.LayoutParams.WRAP_CONTENT,
            true
        ).apply {
            isOutsideTouchable = true
            setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.dropdown_background))
            elevation = 8f
        }

        // 计算下拉菜单位置 - 左对齐，显示在30秒左侧
        val location = IntArray(2)
        getLocationOnScreen(location)
        val x = location[0] + width - dropdownWidth - context.dpFromDimen(R.dimen.spacing_80) // 向左偏移
        val y = location[1]

        popupWindow?.showAtLocation(this, Gravity.NO_GRAVITY, x, y)
    }
    
    /**
     * 计算最大文本宽度
     */
    private fun calculateMaxTextWidth(): Int {
        val paint = android.graphics.Paint()
        paint.textSize = context.spFromDimen(R.dimen.font_16)
        return options.maxOfOrNull { 
            paint.measureText(it).toInt() 
        } ?: 0
    }

    /**
     * 创建下拉菜单视图
     */
    private fun createDropdownView(): View {
        val container = LinearLayout(context).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(
                context.dpFromDimen(R.dimen.spacing_8),
                context.dpFromDimen(R.dimen.spacing_2),
                context.dpFromDimen(R.dimen.spacing_8),
                context.dpFromDimen(R.dimen.spacing_2)
            )
        }

        options.forEachIndexed { index, option ->
            val optionView = createOptionView(option, index == options.lastIndex)
            val optionLP = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                // 为每个选项添加上下左右边距
                topMargin = if(index == 0) context.dpFromDimen(R.dimen.spacing_6) else context.dpFromDimen(R.dimen.spacing_4)
                bottomMargin = if (index == options.lastIndex) context.dpFromDimen(R.dimen.spacing_6) else context.dpFromDimen(R.dimen.spacing_2)
                leftMargin = context.dpFromDimen(R.dimen.spacing_5)
                rightMargin = context.dpFromDimen(R.dimen.spacing_5)
            }
            container.addView(optionView, optionLP)
        }

        return container
    }

    /**
     * 创建选项视图
     */
    private fun createOptionView(option: String, isLast: Boolean): View {
        val optionView = TextView(context).apply {
            text = option
            setTextColor(ContextCompat.getColor(context, R.color.text_primary))
            textSize = context.spFromDimen(R.dimen.font_12)
            setPadding(
                context.dpFromDimen(R.dimen.spacing_16),
                context.dpFromDimen(R.dimen.spacing_8),
                context.dpFromDimen(R.dimen.spacing_16),
                context.dpFromDimen(R.dimen.spacing_8)
            )
            isClickable = true
            isFocusable = true
            gravity = Gravity.CENTER
            maxLines = 1 // 确保一行显示
            ellipsize = android.text.TextUtils.TruncateAt.END
            setTypeface(null, android.graphics.Typeface.BOLD) // 设置字体加粗
        }

        // 设置选中状态背景
        if (option == selectedOption) {
            optionView.background = ContextCompat.getDrawable(context, R.drawable.option_selected_background)
        } else {
            optionView.background = ContextCompat.getDrawable(context, R.drawable.option_background)
        }

        // 设置点击监听器
        optionView.setOnClickListener {
            setSelectedOption(option)
            popupWindow?.dismiss()
            onOptionChangeListener?.invoke(option)
        }

        return optionView
    }
}
